<template>
  <div :class="{'show':show}" class="header-search">
    <svg-icon class-name="search-icon" icon-class="search" @click.stop="click"/>
    <el-select
        ref="headerSearchSelect"
        v-model="search"
        :remote-method="querySearch"
        filterable
        default-first-option
        remote
        placeholder="Search"
        class="header-search-select"
        @change="change"
    >
      <el-option v-for="item in options" :key="item.id" :value="item" :label="item.title"/>
    </el-select>
  </div>
</template>

<script>
import {EvevtBus} from "@/utils/EvevtBus";
import '@/icons/svg/search.svg'
import Request from "@/api/request";

import _ from "lodash"
import {getbyid} from "@/api/docMG";

export default {
  name: 'HeaderSearch',
  data() {
    return {
      search: '',
      options: [],
      searchPool: [],
      show: false,
      fuse: undefined
    }
  },
  watch: {
    show(value) {
      if (value) {
        document.body.addEventListener('click', this.close)
      } else {
        document.body.removeEventListener('click', this.close)
      }
    }
  },
  mounted() {
  },
  methods: {

    click() {
      this.show = !this.show
      if (this.show) {
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
      }
    },
    close() {
      this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur()
      this.options = []
      this.show = false
    },
    async change(val) {
      if (this.$route.name === val.modDbTable) {
        getbyid(val.id, val.modDbTable).then(res => {
          EvevtBus.$emit('data', [res])
        })

      } else {
        var data = await getbyid(val.id, val.modDbTable)
        this.$router.push({name: val.modDbTable, params: {data: [data]}})
      }
      this.search = ''
      this.options = []
      this.$nextTick(() => {
        this.show = false
      })
    },
    querySearch(query) {
      if (query !== '') {
        _.debounce(() => {
          Request.get(`/doc/search?condition=${query}`).then(res => {
            this.options = res
          })
        }, 1000)()
      } else {
        this.options = []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }

  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
